package com.dgut.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dgut.app.service.BillTagService;
import com.dgut.common.dto.BillTagDTO;
import com.dgut.common.entity.BillTag;
import com.dgut.common.entity.UserBillTag;
import com.dgut.common.entity.WxUser;
import com.dgut.common.mapper.BillMapper;
import com.dgut.common.mapper.BillTagMapper;
import com.dgut.common.mapper.UserBillTagMapper;
import com.dgut.common.utils.ApiException;
import com.dgut.common.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author IT00ZYQ
 * @Date 2021/4/6 15:41
 **/
@Service
@Slf4j
public class BillTagServiceImpl implements BillTagService {

    private final BillMapper billMapper;
    private final BillTagMapper billTagMapper;
    private final UserBillTagMapper userBillTagMapper;

    public BillTagServiceImpl(BillMapper billMapper, BillTagMapper billTagMapper, UserBillTagMapper userBillTagMapper) {
        this.billMapper = billMapper;
        this.billTagMapper = billTagMapper;
        this.userBillTagMapper = userBillTagMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBillTag(BillTagDTO dto, String token) {
        WxUser user = JwtUtil.getUser(token);
        QueryWrapper<BillTag> wrapper = new QueryWrapper<>();
        wrapper.eq("name", dto.getName());
        wrapper.eq("type", dto.getType());
        // 查询判断是否存在该标签
        BillTag billTag = billTagMapper.selectOne(wrapper);
        // 不存在则创建
        if (billTag == null) {
            billTag = new BillTag();
            billTag.setName(dto.getName());
            billTag.setType(dto.getType());
            billTagMapper.insert(billTag);
        }

        // 判断用户是否绑定标签
        QueryWrapper<UserBillTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        queryWrapper.eq("tag_id", billTag.getId());
        UserBillTag userBillTag = userBillTagMapper.selectOne(queryWrapper);
        if (userBillTag != null) {
            throw new ApiException("标签已存在");
        }

        // 用户与标签绑定
        userBillTagMapper.insert(UserBillTag.builder()
                .userId(user.getId())
                .tagId(billTag.getId())
                .build());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletedBillTag(Integer tagId, String token) {
        // 不能删除收入和支出标签中的【其他】
        if (tagId == 11 || tagId == 1) {
            throw new ApiException("[其他]标签无法删除");
        }

        BillTag billTag = billTagMapper.selectById(tagId);
        if (billTag == null) {
            throw new ApiException("标签信息不存在");
        }
        WxUser user = JwtUtil.getUser(token);
        QueryWrapper<UserBillTag> wrapper = new QueryWrapper<>();
        wrapper.eq("tag_id", tagId);
        wrapper.eq("user_id", user.getId());
        userBillTagMapper.delete(wrapper);

        // 将用户要删除的标签绑定的账单的标签修改为[其他]
        billMapper.updateBillTag(user.getId(), tagId, billTag.getType() == 0 ? 1:11);
    }

    @Override
    public List<BillTag> listTag(Integer type, String token) {
        WxUser user = JwtUtil.getUser(token);
        QueryWrapper<UserBillTag> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", user.getId());
        List<UserBillTag> userBillTags = userBillTagMapper.selectList(wrapper);
        // 用户没有绑定标签，直接返回空集合，避免下面查询报错
        if (userBillTags == null || userBillTags.size() == 0) {
            return new ArrayList<>();
        }
        List<BillTag> billTags = billTagMapper.selectBatchIds(userBillTags.stream().map(UserBillTag::getTagId).collect(Collectors.toList()));
        // type为1（收入）或0（支出），需要进行类型过滤
        if (type == 1 || type == 0) {
            billTags = billTags.stream().filter(e -> e.getType().equals(type)).collect(Collectors.toList());
        }
        return billTags;
    }
}
